package com.itlong.cloud.intercept;

import com.itlong.cloud.POJO.PO.OperateFunctionPO;
import com.itlong.cloud.POJO.PO.OperateUserInfoPO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.annotation.AuthAccessRequired;
import com.itlong.cloud.enumerate.ecode.OperateErrorCodeEnum;
import com.itlong.cloud.user.operate.IOperateFunctionServiceClient;
import com.itlong.cloud.user.operate.IOperateUserInfoServiceClient;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * <desc>
 *      运营系统权限拦截器。
 * </desc>
 *
 * @createDate 2017/08/29
 */
@Aspect
@Component
public class AuthIntercept {
    private static final Logger LOG = LoggerFactory.getLogger(AuthIntercept.class);
 // 定义一个切入点
    @Pointcut("execution(* com.itlong.cloud.controller..*.*(..))")
    public void excudeService(){}

    @Autowired
    IOperateUserInfoServiceClient userInfoServiceClient;

    @Autowired
    IOperateFunctionServiceClient iOperateFunctionServiceClient;

    @Autowired
    IOperateUserInfoServiceClient iOperateUserInfoServiceClient;
    /**
     * <desc>
     *      方法权限验证拦截器
     * </desc>
     *
     * @param thisJoinPoint
     * @return
     * @author Jiaqi.X
     * @createDate 2017/10/16
     */
    @Around("excudeService() && @annotation(authAccessRequired) && !@annotation(com.itlong.cloud.annotation.UnAuthAccessRequired)")
    public Object twiceAsOld(ProceedingJoinPoint thisJoinPoint,AuthAccessRequired authAccessRequired) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String uri = request.getRequestURI();
        System.out.println (String.format("【%s】请求路由:%s，客户端地址：%s", DateUtil.fomatDate1(new Date()), uri, HttpProtocolUtil.getIpAddr(request)));

        //拿到token
        String token = request.getParameter("token");
        if (token == null) {
            token = request.getAttribute("token") == null ? "" : request.getAttribute("token").toString();
        }
        OperateUserInfoPO user = userInfoServiceClient.retrieve(token);
        //如果拿到的用户为空 交给用户身份验证拦截器处理
        if(user==null||user.getRoleId()==null) {
            return thisJoinPoint.proceed();
        }
        boolean headOff;
        //获取用户角色权限
        List<OperateFunctionPO> list=iOperateFunctionServiceClient.getRoleAuthFunctions(user.getRoleId(),token);
        //判断url是否匹配，匹配则说明用户有权限
        headOff=list.stream().filter(function->StringUtils.isNotBlank(function.getInterceptUrl())&&function.getInterceptUrl().equals(uri)).findFirst().isPresent();
        if(headOff) {
            return thisJoinPoint.proceed();
        }else{
            iOperateUserInfoServiceClient.cancel(token);
            return new MessageVO(OperateErrorCodeEnum.USER_AUTH_ERROR.getErrorCode());
        }
    }
}
